package com.dayuanit.dy16.atm.service.impl;

import com.dayuanit.dy16.atm.entity.Card;
import com.dayuanit.dy16.atm.entity.Flow;
import com.dayuanit.dy16.atm.entity.Message;
import com.dayuanit.dy16.atm.entity.TransferOrder;
import com.dayuanit.dy16.atm.enums.FlowTypeEnum;
import com.dayuanit.dy16.atm.enums.TransferOrderStatusEnums;
import com.dayuanit.dy16.atm.exception.BizException;
import com.dayuanit.dy16.atm.mapper.CardMapper;
import com.dayuanit.dy16.atm.mapper.FlowMapper;
import com.dayuanit.dy16.atm.mapper.MessageMapper;
import com.dayuanit.dy16.atm.mapper.TransferOrderMapper;
import com.dayuanit.dy16.atm.service.ITransferDelayService;
import com.dayuanit.dy16.atm.ws.AtmTextWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

@Service
public class TransferDelayServiceImpl implements ITransferDelayService {
    private static final int delayTime = 10;

    @Autowired
    private CardMapper cardMapper;

    @Autowired
    private FlowMapper flowMapper;

    @Autowired
    private TransferOrderMapper transferOrderMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private AtmTextWebSocketHandler textWebSocketHandler;

    /**
     * 第二步 转账加钱
     * @param transferOrder
     */
    @Transactional
    @Override
    public void transferIn(TransferOrder transferOrder) {
        //如果订单状态不是待转账 则不处理
        if (transferOrder.getStatus() != TransferOrderStatusEnums.wait_transfer.getK()) {
            return;
        }

        Date createTime = transferOrder.getCreateTime();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, -delayTime);

        Date time = cal.getTime();
        if (time.before(createTime)) {
            System.out.println(transferOrder.getId() + "还没到时间");
            return;
        }

        System.out.println(transferOrder.getId() + " 开始处理");

        Card cardIn = cardMapper.get4Lock(transferOrder.getCardInId());
        int newBalance = cardIn.getBalance() + (int)(Double.parseDouble(transferOrder.getAmount()) * 100);

        // 给对方加钱
        int rows = cardMapper.updateBalance(cardIn.getId(), newBalance, cardIn.getBalance());
        if (1 != rows) {
            throw new BizException("转账失败");
        }

        //添加流水
        Flow flow = new Flow();
        flow.setUserId(cardIn.getUserId());
        flow.setRemark(FlowTypeEnum.tranfer_in.getV());
        flow.setFlowType(FlowTypeEnum.tranfer_in.getK());
        flow.setCreateTime(new Date());
        flow.setCardId(cardIn.getId());
        flow.setAmount(transferOrder.getAmount());
        flowMapper.insert(flow);

        //修改转账订单状态
        rows = transferOrderMapper.updateStatus(transferOrder.getId(), TransferOrderStatusEnums.success_transfer.getK(), transferOrder.getStatus());
        if (1 != rows) {
            throw new BizException("转账失败");
        }

        // 生成到账消息
        String msg_patten = "卡号%s到账金额%s元";
        Message message = new Message();
        message.setContext(String.format(msg_patten, cardIn.getCardNum(), transferOrder.getAmount()));
        message.setCreateTime(new Date());
        message.setFromId(transferOrder.getUserId());
        message.setMsgType(1);
        message.setReceiveId(cardIn.getUserId());
        message.setStatus(1);

        messageMapper.insert(message);

        //TODO 推送消息到客户端
        textWebSocketHandler.sendMsg("您有一笔转账金额到账啦", cardIn.getUserId());
    }


    @Transactional
    @Override
    public void transferRollback(TransferOrder transferOrder) {
        if (transferOrder.getStatus() != TransferOrderStatusEnums.rollback_transfer.getK()) {
            return;
        }

        Card cardOut = cardMapper.get4Lock(transferOrder.getCardOutId());
        int newBalance = cardOut.getBalance() + (int)(Double.parseDouble(transferOrder.getAmount()) * 100);

        int rows = cardMapper.updateBalance(cardOut.getId(), newBalance, cardOut.getBalance());
        if (1 != rows) {
            throw new BizException("转账回滚失败");
        }

        //添加流水
        Flow flow = new Flow();
        flow.setUserId(cardOut.getUserId());
        flow.setRemark(FlowTypeEnum.tranfer_rollback.getV());
        flow.setFlowType(FlowTypeEnum.tranfer_rollback.getK());
        flow.setCreateTime(new Date());
        flow.setCardId(cardOut.getId());
        flow.setAmount(transferOrder.getAmount());
        flowMapper.insert(flow);

        // 修改转账订单状态
        rows = transferOrderMapper.updateStatus(transferOrder.getId(), TransferOrderStatusEnums.cancel_transfer.getK(), transferOrder.getStatus());
        if (1 != rows) {
            throw new BizException("转账回滚失败");
        }
    }
}
